<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程类型" prop="courseTypeId">
        <el-select v-model="queryParams.courseTypeId" placeholder="请选择" 
         @keyup.enter.native="handleQuery" clearable >
          <el-option
            v-for="item in typeOptions"
            :key="item.id"
            :label="item.courseTypeName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="课程标签" prop="courseTagId">
        <el-select v-model="queryParams.courseTagId" placeholder="请选择"
          @keyup.enter.native="handleQuery" clearable >
          <el-option
            v-for="item in tagOptions"
            :key="item.id"
            :label="item.tagName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="讲师" prop="teacherId">
        <el-select v-model="queryParams.teacherId" placeholder="请选择"
          @keyup.enter.native="handleQuery" clearable >
          <el-option
            v-for="item in teacherOptions"
            :key="item.id"
            :label="item.teacherName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['curriculum:course:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['curriculum:course:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['curriculum:course:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['curriculum:course:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" :index="createIndex" />
      <el-table-column label="视频封面" align="center" prop="videoPcUrl" >
        <!-- 图片的显示 -->
        <template slot-scope="scope">            
            <img :src="scope.row.videoPcUrl"  min-width="70px" height="70px" 
            @click="previewPic(scope.row.videoPcUrl)" />
        </template>     
      </el-table-column>
      <el-table-column label="课程名称" align="center" prop="courseName">
        <template slot-scope="scope">
          <span @click="viewName(scope.row)">{{scope.row.courseName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程类型" align="center" prop="typeName" />
      <el-table-column label="课程标签" align="center" prop="tagName" >
      </el-table-column>
      <el-table-column label="讲师" align="center" prop="teacherName" />
      <el-table-column label="观看次数" align="center" prop="watchCount" />
      <el-table-column label="推荐状态" align="center" prop="recommendType">
        <template slot-scope="scope">
          <el-switch  v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="设置为轮播图" align="center" prop="isSlideShow" >
        <template slot-scope="scope">
          <el-switch  v-model="scope.row.isSlideShow"
                :active-value="1"
                :inactive-value="0"
                @change="handleIsShowChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="轮播图排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['curriculum:course:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['curriculum:course:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 图片预览   放在表格外面，这是个弹出框-->
    <el-dialog :visible.sync="dialogVisible" :modal="false" title="图片预览" width="50%">
        <img :src="previewpic" alt=""  width="100%" />
        <span slot="footer" class="dialog-footer">
          </span>
       </el-dialog>
  <!-- 图片预览 -->

    <!-- 添加或修改课程视频对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20" style=" display: flex;flex-wrap: wrap;">
        <el-col :lg="12">
          <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程类型" prop="courseTypeId">
          <el-select v-model="form.courseTypeId" placeholder="请选择">
          <el-option
            v-for="item in typeOptions"
            :key="item.id"
            :label="item.courseTypeName"
            :value="item.id">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="课程标签" prop="courseTagId">
          <el-select v-model="form.courseTagId" placeholder="请选择">
    <el-option
      v-for="item in tagOptions"
      :key="item.id"
      :label="item.tagName"
      :value="item.id">
    </el-option>
  </el-select>
        </el-form-item>
        <el-form-item label="讲师" prop="teacherId">
          <el-select v-model="form.teacherId" placeholder="请选择">
    <el-option
      v-for="item in teacherOptions"
      :key="item.id"
      :label="item.teacherName"
      :value="item.id">
    </el-option>
  </el-select>
        </el-form-item>
        <el-form-item label="学习时常" prop="learnTime">
          <el-input v-model="form.learnTime" placeholder="请输入学习时常：单位为分钟比如30分钟" />
        </el-form-item>
        <el-form-item label="视频时长" prop="duration">
          <el-input v-model="form.duration" placeholder="请输入视频时长" />
        </el-form-item>
        <el-form-item label="视频地址" prop="videoUrl">
          <el-upload
            class="avatar-uploader el-upload--text"
            ref="upload"
            :action="upload.url"
            :headers="upload.headers"
            :show-file-list="false"
            :on-success="handleVideoSuccess"
            :before-upload="beforeUploadVideo"
            :on-progress="uploadVideoProcess"
          >
          <video
              v-if="form.videoUrl != '' && videoFlag == false"
              :src="form.videoUrl"
              class="avatar"
              controls="controls"
            >
              您的浏览器不支持视频播放
            </video>
            <i
              v-else-if="form.videoUrl == '' && videoFlag == false"
              class="el-icon-plus avatar-uploader-icon"
            ></i>
            <el-progress
              v-if="videoFlag == true"
              type="circle"
              :percentage="videoUploadPercent"
              style="margin-top:30px;"
            ></el-progress>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频封面" prop="videoPcUrl">
          <el-upload
  class="avatar-uploader"
  ref="videoUpload"
  :action="videoUpload.url"
  :headers="videoUpload.headers"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  >
  <img v-if="form.videoPcUrl" :src="form.videoPcUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
        </el-form-item>
       
        </el-col>
        <el-col :lg="12">
          <el-form-item label="课程介绍" prop="courseTitle">
            <div class="divList">
            <div style="max-height: 650px" class="contentContainer">
            <editor v-model="form.courseTitle" :min-height="650"/>
            </div>
          </div>
        </el-form-item>
        </el-col>
        </el-row>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="viewOpen" :modal="false" :title="title" width="50%">
   <el-form ref="form" :model="form">
<div style="width: 100%" class="previewWrapper">
	<div class="previewContainer">
		<div class="card" style="padding:10px 10px 10px 10px;text-align:left;display: none" >
		</div>
		<div class="card" style="padding:10px 10px 10px 10px;text-align:center;display: none">
		</div>
		<div class="card" style="text-align:center;display: none">
		</div>
		<div class="card" style="padding:10px 10px 10px 10px;display: none">
		</div>
		<div style="max-height: 667px" class="contentContainer">
			<div style="margin-bottom: 10px">
				<strong style="font-size: 18px;">{{form.courseName}}</strong>
			</div>
			<span v-html="form.courseTitle"></span>
		</div>
	</div>
</div>
   </el-form>
 </el-dialog>
  </div>
</template>

<script>
import { listCourse, getCourse, delCourse, addCourse, updateCourse,listType,listTag,listTeacher,changeStatus,changeIsShow } from "@/api/curriculum/course";

import { getToken } from "@/utils/auth";
export default {
  name: "Course",
  data() {
    return {
      dialogVisible: false,
      previewpic: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程视频表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      viewOpen:false,
        //上传参数
        upload:{
          // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/curriculum/course/uploadVideo"
      },
      videoUpload:{
      // 设置上传的请求头部
      headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
      url: process.env.VUE_APP_BASE_API + "/content/press/importData"    
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseName: null,
        courseTypeId: null,
        courseTagId: null,
        courseTitle: null,
        hourCatalogId: null,
        learnTime: null,
        pcUrl: null,
        duration: null,
        videoUrl: null,
        videoPcUrl: null,
        teacherId: null,
        price: null,
        discountsPrice: null,
        collectCount: null,
        watchCount: null,
        integral: null,
        asId: null,
        status: null,
        recommendType: null,
        videoId: null,
        isSlideShow: null,
        sort: null
      },
      typeOptions:[],
      tagOptions:[],
      teacherOptions:[],
      videoFlag:false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    createIndex(index){
      return (this.queryParams.pageNum-1)*(this.queryParams.pageSize+index+1);
    },
    /** 查询课程视频列表 */
    getList() {
      this.loading = true;
      listCourse(this.queryParams).then(response => {
        console.info(response);
        this.courseList = response.list.rows;
        this.total = response.list.total;
        this.typeOptions=response.type;
        this.tagOptions=response.tag;
        this.teacherOptions=response.teacher;
        this.loading = false;
      });
    },
           // 状态修改
      handleStatusChange(row) {
      console.info(row.status);
      let text = row.status == 1 ? "推荐" : "不推荐";
      this.$modal.confirm('确认要"' + text + '""' + row.courseName+ '"视频吗？').then(function() {
        return changeStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    }, 
               // 状态修改
    handleIsShowChange(row) {
      console.info(row.isSlideShow);
      let text = row.isSlideShow == 1 ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.courseName+ '"视频吗？').then(function() {
        return changeIsShow(row.id, row.isSlideShow);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.isSlideShow === "0" ? "1" : "0";
      });
    }, 
      
    //查看视频介绍
    viewName(row){
      this.form=row;
      this.viewOpen=true;
      this.title="查看介绍";
    },
    //图片放大
    previewPic(url) {
     this.previewpic = url;
    this.dialogVisible = true;
        },
   // 验证视频格式
   beforeUploadVideo(file) {
      if (
        [
          'video/mp4',
          'video/ogg',
          'video/flv',
          'video/avi',
          'video/wmv',
          'video/rmvb'
        ].indexOf(file.type) === -1
      ) {
        this.$message.error('请上传正确的视频格式')
        return false
      }
    },
      // 上传进度显示
      uploadVideoProcess(event, file, fileList) {
      console.log(event.percent, file, fileList)
      this.videoFlag = true
      this.videoUploadPercent = Math.floor(event.percent)
    },
        // 获取上传图片地址
    handleVideoSuccess(res, file) {
      this.videoFlag = false
      this.videoUploadPercent = 0
      if (res.code === 200) {
        console.log(res.data.url)
        this.form.videoUrl = res.data.url;
      } else {
        this.$message.error('视频上传失败，请重新上传！')
      }
    },  
    handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        if(res.code=200){
          console.info(res);
          this.form.videoPcUrl=res.data;
        }else{
          this.$message.error('封面上传失败,请重新上传');
        }
        
      },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        courseName: null,
        courseTypeId: null,
        courseTagId: null,
        courseTitle: null,
        hourCatalogId: null,
        learnTime: null,
        pcUrl: null,
        duration: null,
        videoUrl: null,
        videoPcUrl: null,
        teacherId: null,
        price: null,
        discountsPrice: null,
        collectCount: null,
        watchCount: null,
        integral: null,
        asId: null,
        status: 0,
        createTime: null,
        updateTime: null,
        recommendType: null,
        videoId: null,
        isSlideShow: null,
        sort: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      listType().then(res=>{
        console.info(res)
        this.typeOptions=res.data;
      });
      listTag().then(res=>{
        console.info(res);
        this.tagOptions=res.data;
      });
      listTeacher().then(res=>{
        console.info(res);
        this.teacherOptions=res.data;
      })
      this.title = "添加课程视频";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCourse(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改课程视频";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCourse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCourse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除课程视频编号为"' + ids + '"的数据项？').then(function() {
        return delCourse(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('curriculum/course/export', {
        ...this.queryParams
      }, `course_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.divList{
  height: 650px;
  border-radius: 1px;
  border-style:solid;
  border-width:1px;
}
.previewWrapper{
		display: flex;
		justify-content: center;
	}
.previewContainer{
		width: 400px !important;
		height: 667px !important;
		background-image: url("https://shequncloud.oss-cn-shenzhen.aliyuncs.com/material/phoneKK.png");
		background-repeat: no-repeat;
		background-size: 100% 100%;
		padding: 85px 35px 86px 35px;
		box-sizing: border-box;
		position: relative;
	}
.contentContainer{
    height: 100%;
		overflow-y: auto;
		overflow-x: hidden;
	}
.contentContainer::-webkit-scrollbar {
  display: none;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9 !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px !important;
  position: relative !important;
  overflow: hidden !important;
}
.avatar-uploader .el-upload:hover {
  border: 1px dashed #d9d9d9 !important;
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 300px;
  height: 178px;
  display: block;
}
</style>
